/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bionic.socialNet.command;

import com.bionic.socialNet.commandBeans.UserBean;
import com.bionic.socialNet.entities.LoginData;
import com.bionic.socialNet.entities.ProfileData;
import static com.bionic.socialNet.manager.AttributeNames.*;
import com.bionic.socialNet.manager.Config;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Ann
 */
public class CommandLogin implements ICommand {

    private static final String LOGIN = "login";
    private static final String PASSWD = "password";

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
        //return Config.getInstance().getProperty(Config.LOGIN);
        // check login pass
        String page = null;
        
        UserBean user = new UserBean();
        LoginData loginData = new LoginData();
        loginData.setLogin(request.getParameter(LOGIN));
        loginData.setPassword(request.getParameter(PASSWD));

        boolean isLogin = user.isLogin(loginData);
        try {
            if (isLogin) {
                ProfileData profile = user.getUserProfile();
                request.setAttribute(FULL_NAME, profile.getFullname());
                request.setAttribute(NICKNAME, profile.getNickname());
                request.setAttribute(BIRHDAY, profile.getBirthday());
                request.setAttribute(ABOUT, profile.getAbout());
                request.setAttribute(USER_ID, profile.getUserId());
                // if found user - set user_id attribute for session
                request.getSession().setAttribute(USER_ID, profile.getUserId()); 
                
                page = Config.getInstance().getProperty(Config.USER_PROFILE);
            } else {
                // send error message to error page
                request.setAttribute(ERROR_MESSAGE, "User not found. Check email and password");
                page = Config.getInstance().getProperty(Config.ERROR);
            }
        } catch (Exception ex) {
            Logger.getLogger(CommandLogin.class.getName()).log(Level.SEVERE, null, ex);
             page = Config.getInstance().getProperty(Config.ERROR);
        }

        return page;
    }
}
